import { getGuideList } from '../../api/guide'
import { login, isLogin } from '../../utils/login'

Page({

  /**
   * 页面的初始数据
   */
  data:<any> {
    isEnd: false,
    showIcon: false,
    showDropdown: false,
    guideName: '',
    guideList: [],
    params: {
      pageNum: 1,
      pageSize: 300
    },
    currentGuide: null,
    hotestList: [],
    taskId: null
  },

  onShow(){
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }

    if(isLogin()){
      if(getApp().globalData.guideList.length > 0){
        const list = getApp().globalData.guideList
        this.setData({
          guideList: list,
          searchGuideList: list
        })
      }else{
        this.getGuideListHandle()
      }
    }
  },

  lazySearch(e){
    const name = e.detail.value
    const list = this.data.guideList.filter(item => {
      return item.name.indexOf(name) > -1
    })

    this.setData({
      guideName: name,
      searchGuideList: list
    })
  },

  getGuideListHandle(){
    const query: any = {
      ...this.data.params
    }
    if(this.data.guideName){
      query.name = this.data.guideName
    }
    getGuideList(query).then(res => {
      if(typeof res.total !== 'undefined'){
        this.setData({
          params: {
            ...this.data.params,
            totalNum: res.total
          }
        })
      }
      
      if(res.rows && res.rows.length > 0){
        this.setData({
          searchGuideList: res.rows,
          guideList: res.rows
        })
        getApp().globalData.guideList = res.rows
      }else{
        this.setData({
          searchGuideList: [],
          guideList: []
        })
      }
    })
  },

  // 点击切换 
  selectbtn(event: any) {
    let index = event.currentTarget.dataset.index
    this.setData({
      active: index
    })
    
    // 绑定分享参数
    wx.onCopyUrl(() => {
      return { query: `active=${this.data.active}` }
    })
  },

  // 跳转函数，参数为携带的数据索引
  chatRouter(guide) {
    wx.navigateTo({
      url: '/pages/chat/chat',
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', guide)
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  },

  /**
   * 进入对话
   */
  enterChat(){
    if(!this.data.currentGuide){
      return
    }
    this.chatRouter({
      currentGuide: this.data.currentGuide
    })
  },

  /**
   * 下拉
   */
  showModal(){
    this.setData({
      showDropdown: !this.data.showDropdown
    })
  },

  choseGuide(event){
    const guide = event.currentTarget.dataset.item
    this.setData({
      showDropdown: false,
      currentGuide: guide
    })

    this.chatRouter({
      currentGuide: this.data.currentGuide
    })
  }
})